/* This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.gnarly.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * Console.java
 * 
 * Handles all the console related such as commands
 * 
 * @author gnarly
 */
public class Console {

	public BufferedReader input;

	private final String[] commands = { ".help", ".commands", ".disconnect" };

	private static BufferedReader in;
	private final PrintWriter out;
	
	private Client client;

	public Console(final InputStream inStream, final OutputStream outStream, final Client client) {
		in = new BufferedReader(new InputStreamReader(inStream));
		out = new PrintWriter(outStream);
		this.client = client;
	}

	public void processCommand(final String command) throws IOException {
		int index = -1;
		for (int i = 0; i < commands.length; i++) {
			if (command.equalsIgnoreCase(commands[i])) {
				index = i;
				break;
			}
		}
		switch (index) {
			case -1:
				break;
			case 0:
				out.println("Type .commands for a list of commands");
				out.println();
				out.flush();
				break;
			case 1:
				String commandsList = "List of commands: [";
				for (int i = 0; i < commands.length; i++) {
					if (i != 0) {
						commandsList += ", ";
					}
					commandsList += commands[i];
				}
				commandsList += "]";
				out.println(commandsList);
				out.println();
				out.flush();
				break;
			case 2:
				client.setDisconnected(true);
				break;
			default:
				out.println("That command does not exist!");
				out.println();
				out.flush();
				break;
		}
	}

	public void run() {
		try {
			while (!client.isDisconnected()) {
				if (in.readLine() != null) {
					processCommand(in.readLine());
				}
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}
	
}
